package com.guava.mall.tool.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.guava.mall.tool.common.base.BaseDao;
import com.guava.mall.tool.common.base.BaseService;
import com.guava.mall.tool.common.constant.ImageStatusEnum;
import com.guava.mall.tool.common.constant.ProductFileEnum;
import com.guava.mall.tool.common.constant.Symbol;
import com.guava.mall.tool.common.utils.ImageFileUtils;
import com.guava.mall.tool.common.utils.ImageProvider;
import com.guava.mall.tool.common.utils.PathUtils;
import com.guava.mall.tool.dao.ImageInfoDao;
import com.guava.mall.tool.entity.ImageInfo;
import com.guava.mall.tool.model.ImageInputDto;
import com.guava.mall.tool.service.ImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @Description:
 * @Auth: DengYunHu
 * @Date: 2021/4/1 15:07
 */
@Slf4j
@Service
public class ImageServiceImpl implements ImageService, BaseService<ImageInfo> {

    @Autowired
    private ImageInfoDao imageInfoDao;

    @Override
    public BaseDao getDao() {
        return this.imageInfoDao;
    }


    @Override
    public void bindMarkInfo(ImageInputDto markInfo) {
        ImageInfo info = imageInfoDao.findById(markInfo.getId()).orElse(null);
        if (Objects.isNull(info) || StrUtil.isBlank(markInfo.getMarkInfo())) {
            log.info("info is null");
            return;
        }
        try {
            String mark = Optional.ofNullable(markInfo.getMarkInfo()).orElse("");
            if (StrUtil.equals(mark, info.getMarkInfo())) {
                log.info("原来的值保持不变，不做修改");
                return;
            }
            String sourceUrl = info.getSourceUrl();
            String sourcePath = ImageFileUtils.uriToPath(sourceUrl);
            if (StrUtil.isBlank(sourcePath) || !FileUtil.exist(sourcePath)) {
                log.info("source file not exits");
                info.setStatus(ImageStatusEnum.IMAGE_NOT_FOUND.getDesc());
                imageInfoDao.save(info);
                return;
            }
            String oldTargetUri = info.getTargetUrl();
            String markFileName = markInfo.getMarkInfo() + "_" + IdUtil.fastSimpleUUID() + Symbol.DOT + FileUtil.extName(info.getSourceImageName());
            String markPath = PathUtils.markPath()
                    .concat(markFileName);
            ImageProvider.addLayer(sourcePath, markInfo.getMarkInfo(), markPath);
            String markUri = ImageFileUtils.pathToUri(markPath);

            info.setTargetUrl(markUri);
            info.setTargetImageName(markFileName);
            info.setStatus(ImageStatusEnum.MARK_SUCCESS.getDesc());
            info.setMarkInfo(markInfo.getMarkInfo());
            imageInfoDao.save(info);
            if (StrUtil.isNotBlank(oldTargetUri)) {
                String oldPath = ImageFileUtils.uriToPath(oldTargetUri);
                FileUtil.del(oldPath);
            }

        } catch (Exception e) {
            log.error("error", e);
            info.setStatus(ImageStatusEnum.UPLOAD_NOT_HANDLE.getDesc());
            imageInfoDao.save(info);

        }

    }

    @Override
    public void deleteImages(List<Long> idList) {
        for (Long imageId : idList) {
            ImageInfo info = imageInfoDao.findById(imageId).orElse(null);
            if (Objects.isNull(info)) {
                continue;
            }
            String sourceFile = ImageFileUtils.uriToPath(info.getSourceUrl());
            String targetFile = ImageFileUtils.uriToPath(info.getTargetUrl());

            FileUtil.del(sourceFile);
            FileUtil.del(targetFile);
            imageInfoDao.deleteById(imageId);
        }
    }

    @Override
    public Page<ImageInfo> findImageList(Pageable page) {
        return imageInfoDao.findAll(page);
    }

    @Override
    public boolean uploadImage(MultipartFile[] file) {
        for (MultipartFile multipartFile : file) {
            String originalFilename = multipartFile.getOriginalFilename();
            String extName = FileUtil.extName(originalFilename);
            String imagePath = ImageFileUtils.createFilePath(ProductFileEnum.IMAGE.getType(), IdUtil.fastSimpleUUID(), extName);
            try {
                multipartFile.transferTo(new File(imagePath));
                String uri = ImageFileUtils.pathToUri(imagePath);
                this.saveUploadImageInfo(uri, originalFilename);
            } catch (Exception e) {
            }
        }

        return false;
    }


    @Override
    public String exportZipFile(List<Long> imageIdList) {

        return null;
    }

    public void saveUploadImageInfo(String sourceUrl, String sourceImageName) {
        ImageInfo imageInfo = new ImageInfo();
        imageInfo.setSourceUrl(sourceUrl);
        imageInfo.setSourceImageName(sourceImageName);
        imageInfo.setStatus(ImageStatusEnum.UPLOAD_NOT_HANDLE.getDesc());
        imageInfoDao.save(imageInfo);
    }
}
